'use strict';
module.exports = {
	/**
	 * XXXnameXXX
	 * @url client/pages/kh/index_userdata 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {
		let {
			data = {}, userInfo, util, filterResponse, originalParam
		} = event;
		let {
			customUtil,
			uniID,
			config,
			pubFun,
			vk,
			db,
			_
		} = util;
		let {
			uid,
			todatStart
		} = data;
		let res = {
			code: 0,
			msg: "",
			todaySign: false,
			last_view: {},
			clickid: ""
		};
		res.userInfo = userInfo;
		// 业务逻辑开始-----------------------------------------------------------
		var nowtime = new Date().getTime()

		//====检查今日是否签到====
		const check_signCount = await db.collection('a_sign').where({
			user_id: userInfo._id,
			_add_time: _.gte(todatStart)
		}).count()
		if (check_signCount.total > 0) {
			res.todaySign = true
		}
		//====检查今日是否签到结束====

		//====获取用户的观看历史记录====
		const last_view = await db.collection('a_history').where({
			user_id: userInfo._id
		}).orderBy('_add_time', 'desc').limit(1).get()
		res.last_view = last_view.data[0]
		//====获取用户的观看历史记录结束====


		//===改变用户的会员状态
		if (userInfo.plus_type == 0) {
			console.log("用户非会员");
		}
		//判断用户的会员到期没有，到期的话就把plus_type改为0
		let plus_type = userInfo.plus_type
		let plus_expire_time = userInfo.plus_expire_time
		if (plus_expire_time < nowtime && plus_type == 1) {
			console.log("用户会员已过期，改为普通用户");
			let updateVip = await db.collection('uni-id-users').doc(userInfo._id).update({
				plus_type: 0
			})
		}
		res.plus_expire_time = plus_expire_time
		res.nowtime = nowtime

		// //如果用户信息里没有城市信息，则自动添加
		// if (!userInfo.city) {
		// 	//获取用户的地区信息
		// 	let userip = originalParam.context.CLIENTIP;
		// 	let ipurl = "http://whois.pconline.com.cn/ipJson.jsp?ip=" + userip + "&json=true";
		// 	let ip_result = await uniCloud.httpclient.request(ipurl, {
		// 		method: 'GET',
		// 		data: {},
		// 		contentType: 'json',
		// 		dataType: 'json'
		// 	})

		// 	let bind_address = await db.collection('uni-id-users').doc(userInfo._id).update({
		// 		province: ip_result.data.pro,
		// 		city: ip_result.data.city,
		// 	})
		// }

		//====修改用户的推广平台信息开始====
		//如果用户信息里存在clue_token，且不存在tg_pt，则更新用户推广平台为douyin
		if (userInfo.clue_token && !userInfo.tg_pt) {
			let update_tg_pt = await db.collection('uni-id-users').doc(uid).update({
				tg_pt: "douyin"
			})

			//======获取抖音回传参数======
			let percent = await db.collection('a_config').where({
				name: "RebackPercent",
				user_id: userInfo.invite_code || 0 //添加这条数据的代理商ID
			}).get()

			if (percent.data[0]) {
				//回传用户激活数据
				let url = percent.data[0].douyin_url; //抖音广告资产化回传URL
				let token = percent.data[0].douyin_token; //抖音广告资产化回传token
				let nonce = 8889;
				let times = vk.pubfn.toDecimal(new Date() / 1000, 0);
				const crypto = require('crypto');
				const sha1 = crypto.createHash('sha1');
				let strList = [token, times, nonce];
				strList.sort();
				let buffer = "";
				strList.forEach(str => {
					buffer += str;
				})
				let sign = sha1.update(buffer).digest('hex');

				let reback_url = url + "?timestamp=" + times + "&nonce=" + nonce + "&signature=" + sign;
				let jh_result = await uniCloud.httpclient.request(reback_url, {
					method: 'POST',
					data: {
						"clue_token": userInfo.clue_token,
						"open_id": userInfo.wx_openid['mp-weixin'],
						"event_type": "0", //参考：https://bytedance.feishu.cn/docx/doxcnmjDmhXc1Vial05xpvdu9ed
						"props": {
							"pay_amount": 0 //单位：分
						}
					},
					contentType: 'json',
					dataType: 'json'
				})
				console.log("激活回传结果=", jh_result);
				let update_reback1 = await db.collection('uni-id-users').doc(userInfo._id).update({
					reback: 1,
					rebacklog: "log:" + userInfo.clue_token
				})
			}
		}
		//====修改用户的推广平台信息结束====


		//判断用户是否有H5支付历史开始
		// let check_h5pay = await db.collection('a_h5pay').where({
		// 	pay_state: 1,
		// 	state: 0,
		// 	openid: userInfo.wx_openid['mp-weixin']
		// }).limit(1).get()
		// if (check_h5pay.data.length == 1) {
		// 	if (check_h5pay.data[0]._id.length > 10) {
		// 		//修改记录的状态值
		// 		let up_h5pay_state = await db.collection('a_h5pay').doc(check_h5pay.data[0]._id).update({
		// 			state: 1
		// 		})

		// 		let add_bean = check_h5pay.data[0].bean_number * 1;

		// 		//给对应的用户加金豆
		// 		let add_bean_log = await db.collection('uni-id-users').where({
		// 			['wx_openid.mp-weixin']: userInfo.wx_openid['mp-weixin']
		// 		}).update({
		// 			balance: _.inc(add_bean)
		// 		})

		// 		let add1 = await db.collection('a_jindou_detail').add({
		// 			user_id: userInfo._id,
		// 			nickname: userInfo.nickname,
		// 			change_num: add_bean,
		// 			change_reason: "H5支付充值" + add_bean + "金豆",
		// 			type: "income",
		// 			appid: userInfo.appid,
		// 			appname: userInfo.appname,
		// 			_add_time: nowtime
		// 		})
		// 	}
		// }
		//判断用户是否有H5支付历史结束
		// let add = await db.collection('vk-test').add({
		// 	tips: "抖音小程序激活回传161",
		// 	user_id: userInfo._id,
		// 	creativetype: userInfo.creativetype,
		// 	_add_time: nowtime
		// })


		//   新增内容
		if (userInfo.creativetype && userInfo.reback == 0) {
			await dyxcx_callback() //抖音小程序巨量回传
		}

		//====判断用户是否已绑定广告平台信息====
		//用户已绑定广告平台的信息，则直接返回res
		if (userInfo.tg_pt || userInfo.clue_token) {
			return res;
		}


		//未绑定则继续执行：通过客户端IP查找jl_chudian里最后一条此IP的callback,且必须是一个小时内记录的，并通过此callback回传信息给巨量
		let ip = originalParam.context.CLIENTIP;
		let chudian_info = await db.collection('jl_chudian').where({
			ip: ip,
			time: _.gt(nowtime - 3600000)
		}).orderBy('time', 'desc').limit(1).get()
		//如果没找到该IP对应的触点信息,则直接返回res
		if (chudian_info.data.length != 1) {
			return res;
		}

		//把ad_id和clickid带回客户端
		res.tg_pt = chudian_info.data[0].pt || "pt"; //平台
		res.ad_id = chudian_info.data[0].ad_id || "ad_id"; //广告主账号ID
		res.aid = chudian_info.data[0].aid || "aid"; //广告计划id
		res.cid = chudian_info.data[0].cid || "cid"; //广告创意id
		res.clickid = chudian_info.data[0].callback || "";


		//有clickid和ad_id时，绑定到用户信息里面
		let bind_adid = await db.collection('uni-id-users').doc(userInfo._id).update({
			tg_pt: res.tg_pt,
			ad_id: res.ad_id, //广告主账号ID
			aid: res.aid, //广告计划id
			cid: res.cid, //广告创意id
			clickid: res.clickid,
			pageId: chudian_info.data[0].pageId //oppo广告专属-网页ID
		})

		//如果找到了clickid且该用户激活信息未回传，就做一次激活回传。

		//快手：https://ad.kuaishou.com/
		if (res.tg_pt == "kuaishou" && userInfo.reback == 0) {
			//回传激活信息给快手
			let ksurl = "http://ad.partner.gifshow.com/track/activate?event_type=1&event_time=" + nowtime +
				"&callback=" + res.clickid
			let kshuichuan_result = await uniCloud.httpclient.request(ksurl, {
				method: 'GET',
				data: {},
				contentType: 'json',
				dataType: 'json'
			})
			let ks_update_reback = await db.collection('uni-id-users').doc(userInfo._id).update({
				reback: 1
			})
		}

		//巨量引擎：https://www.oceanengine.com/
		if (res.tg_pt == "douyin" && userInfo.reback == 0) {
			// 回传关键页面触发事件给巨量，参考文档：http://event-manager.oceanengine.com/docs/8650/h5_api_docs/
			//转化回传事件全集：https://event-manager.oceanengine.com/docs/8650/all_events/
			let jlurl = "https://analytics.oceanengine.com/api/v2/conversion"
			let tthuichuan_result = await uniCloud.httpclient.request(jlurl, {
				method: 'POST',
				data: {
					"event_type": "active",
					"context": {
						"ad": {
							"callback": res.clickid, //callback，填写clickid
						}
					},
					"timestamp": nowtime
				},
				contentType: 'json', // 指定以application/json发送data内的数据
				dataType: 'json' // 指定返回值为json格式，自动进行parse
			})
			let dy_update_reback = await db.collection('uni-id-users').doc(userInfo._id).update({
				reback: 1
			})
		}

		//UC超级汇川：e.uc.cn
		if (res.tg_pt == "uc" && userInfo.reback == 0) {
			console.log("执行用户登录时间给UC回传");
			// 回传支付事件给UC广告平台https://www.yuque.com/chaojihuichuan/hhcp03/li07c0?singleDoc=
			let nows = new Date().getTime()
			let purchase_amount = 1;
			let ucurl = res.clickid + "&type=65&money=" + purchase_amount + "&event_time=" + nows
			let uchuichuan_result = await uniCloud.httpclient.request(ucurl, {
				method: 'GET',
				data: {},
				contentType: 'json',
				dataType: 'json'
			})
			//UC返回成功形式为{"status":0}
			let uc_update_reback = await db.collection('uni-id-users').doc(userInfo._id).update({
				reback: 1
			})
		}

		//腾讯广点通：e.qq.com
		if (res.tg_pt == "tengxun" && userInfo.reback == 0) {
			let nows = new Date().getTime()
			let ts_10 = Math.round(new Date().getTime() / 1000).toString();
			// 回传支付事件给腾讯https://docs.qq.com/pdf/DQm1PUWRHZVdudkRG?
			//回传事件类型：https://developers.e.qq.com/docs/guide/conversion/new_version/Web_api
			let tengxunurl =
				"http://tracking.e.qq.com/conv/web?clickid=" + res.clickid + "&action_time=" + ts_10 +
				"&action_type=VIEW_CONTENT&link=tracking.e.qq.com";
			let tengxunhuichuan_result = await uniCloud.httpclient.request(tengxunurl, {
				method: 'GET',
				data: {},
				contentType: 'json',
				dataType: 'json'
			})
			let tx_update_reback = await db.collection('uni-id-users').doc(userInfo._id).update({
				reback: 1
			})
		}


		// 业务逻辑结束-----------------------------------------------------------
		return res;


		//   新增内容
		async function dyxcx_callback() {
			let jlurl = "https://analytics.oceanengine.com/api/v2/conversion"
			let tthuichuan_result = await uniCloud.httpclient.request(jlurl, {
				method: 'POST',
				data: {
					"event_type": "active",
					"context": {
						"ad": {
							"callback": userInfo.clickid, //callback，填写clickid
						}
					},
					"timestamp": nowtime
				},
				contentType: 'json', // 指定以application/json发送data内的数据
				dataType: 'json' // 指定返回值为json格式，自动进行parse
			})
			// 付费回传方式
			// let jlurl = "https://ad.toutiao.com/track/activate/?callback=" + userInfo.clickid +
			// 	"&event_type=0"
			// let tthuichuan_result = await uniCloud.httpclient.request(jlurl, {
			// 	method: 'GET',
			// 	data: {},
			// 	contentType: 'json',
			// 	dataType: 'json'
			// })

			let add = await db.collection('vk-test').add({
				tips: "抖音小程序激活回传analytics",
				user_id: userInfo._id,
				clickid: userInfo.clickid,
				tthuichuan_result: tthuichuan_result,
				jlurl: jlurl
			})

			let dyxcx_update_reback = await db.collection('uni-id-users').doc(userInfo._id).update({
				reback: 1,
				tg_pt: "douyin"
			})
		}
	}
}